﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;

namespace Tests
{
	class InlinePdfHtmlDocumentMatcher : IPageMatcher
	{
		private static readonly ContentType pdfContentType = new ContentType("application/pdf");

		public bool Matches(Page page)
		{
			var embedElement = page.Document.DocumentNode.SelectSingleNode("/html/body/embed");
			if (embedElement != null)
			{
				var sourceAddressAttribute = embedElement.Attributes["src"];
				if (sourceAddressAttribute != null)
				{
					var sourceAddress = new Uri(sourceAddressAttribute.Value);
					if (sourceAddress == page.Address)
					{
						var contentTypeAttribute = embedElement.Attributes["type"];
						if (contentTypeAttribute != null)
						{
							var contentType = new ContentType(contentTypeAttribute.Value);
							return IsMatching(contentType);
						}
					}
				}
			}

			return false;
		}

		private static bool IsMatching(ContentType contentType)
		{
			return contentType.MediaType.Equals(pdfContentType.MediaType, StringComparison.OrdinalIgnoreCase);
		}
	}
}
